/*需要您手动修改baas代码，没有了解baas的请先了解baas的原理！然后参照apache-tomcat\webapps\baas\src\com\justep\templates\Test.java
修改数据库的库名和表名即可
另外需要修改：
	配置数据源：apache-tomcat\webapps\baas\META-INF\context.xml
				（修改时手动同步：apache-tomcat\conf\Catalina\localhost\baas.xml）
	映射		：apache-tomcat\webapps\baas\WEB-INF\web.xml 
	url     :下边代码中的Baas.sendRequest方法中的url要和web.xml中的配置一致
*/


define(function(require){
	var $ = require("jquery");
	var justep = require("$UI/system/lib/justep");
	var check = require("$UI/communityOto/common/check");
	
	
	var Model = function(){
	    this.fileList = [];
	    this.imgSrc = '';
	    this.imgSrcList = [];
	    this.addImgList = [];
	    this.imgSelectIndex = -1;//当前选择的图片index
	    this.selectAreaId = justep.Bind.observable('');
	    this.emailOk = true;
	    this.nameOk = true;
	    this.phoneOk = true;
	    this.isOfficeChange = false;//用于标记小区更改按钮的状态
	    this.areaName = justep.Bind.observable('');
	    this.areaAddress = justep.Bind.observable('');
	    this.areaEmail = justep.Bind.observable('');
		this.callParent();
	};


	
	Model.prototype.MyInforDataCustomRefresh = function(event){
		var userInfo = JSON.parse(localStorage.getItem("userInfo"));
		console.log(userInfo);
		this.comp("MyInforData").newData({
			"defaultValues":[{"fID":justep.UUID.createUUID(),
			               "name":userInfo.userName,
			               "sex":userInfo.sex,
			               "phone":userInfo.phone,
			               "email":userInfo.email}]
		});
		
	};
	
	Model.prototype.areaDataCustomRefresh = function(event){
	    var companyId = this.getParentModel().getCompanyId();
		var url = "http://www.xjzlhy.com:81/ex_community/a/api/community/findChildById?callback=?";
		var me=this;
		$.getJSON(url,{"id":companyId},function(data){
			me.comp("areaData").loadData(data.data);
		});
		//me.comp("areaData").refreshData();

	};
	
	Model.prototype.changeInfoBtnClick = function(event){
	
	    var name = this.comp("name").val();
	    var sex = this.comp("sex").val();
	    var email = this.comp("email").val();
	    var phone = this.comp("phone").val();
	    var userInfo = JSON.parse(localStorage.getItem("userInfo"));
	    
	    if(userInfo.userName == name && userInfo.sex == sex && userInfo.phone == phone && userInfo.email == email){
	         justep.Util.hint("未修改任何信息",{type:"danger"});    
	    }else{
	        if(this.emailOk && this.phoneOk && this.nameOk){
	        	var userId = userInfo.userId;
	        	var url = "http://www.xjzlhy.com:81/ex_community/a/api/community/modifyMobileInfo?callback=?";
	        	 $.getJSON(url,
				        {
				            id:userId,
				        	name:name,
				        	sex:sex,
				        	email:email,
				        	phone:phone
				        },
				        function(data){
				        	userInfo.userName = name;
				        	userInfo.sex = sex;
				        	userInfo.email = email;
				        	userInfo.phone = phone;        	
				        	localStorage.setItem("userInfo", JSON.stringify(userInfo));
				        	justep.Util.hint('更换信息成功', {type:'success'});
				        }
		        );
	        }else{
	        	justep.Util.hint("所填信息存在错误",{type:"danger"});  
	        }
	    }
	    
	};
	
	Model.prototype.nameBlur = function(event){
	   
		if(!check.testName(this.comp("name").val())){
		    this.nameOk = false;
			justep.Util.hint("请输入正确的中文名字",{type:"danger"});
		}else{
			this.nameOk = true;
		}

	};
	
	Model.prototype.emailBlur = function(event){
		if(!check.testEmail(this.comp("email").val())){
		    this.emailOk = false;
			justep.Util.hint("请输入正确的邮箱格式",{type:"danger"});
		}else{
			this.emailOk = true;
		}
	};
	
	Model.prototype.phoneBlur = function(event){
	    
		if(!check.testPhone(this.comp("phone").val())){
		    this.emailOk = false;
			justep.Util.hint("请输入正确的电话格式",{type:"danger"});
		}else{
			this.phoneOk =  true;
		}
	};
	
	
	Model.prototype.check = check;
	
	
	//修改小区按钮
	Model.prototype.changeOfficeClick = function(event){
		
		if(!this.isOfficeChange){
			$('#'+this.getIDByXID("areaName")).hide();
		    $('#'+this.getIDByXID("select1")).show();
		    this.comp("changeOffice").set({label:'保存'});
		    this.isOfficeChange = true;
		}else{
		   
		    var userId = JSON.parse(localStorage.getItem("userInfo")).userId;
		    var me = this;
		    if(this.selectAreaId.get()){
		        var changAreaUrl = 'http://www.xjzlhy.com:81/ex_community/a/api/community/changeNeighborhood?callback=?&office.id='+this.selectAreaId.get()+'&id='+userId;
		    	$.getJSON(
				    changAreaUrl,
				    function(data){
				    	justep.Util.hint('更换小区成功', {type:'success'});
				    	localStorage.setItem('userInfo', JSON.stringify(data));
				    	me.areaName.set(JSON.parse(localStorage.getItem('officeInfo')).name);
				        me.areaAddress.set(JSON.parse(localStorage.getItem('officeInfo')).address);
                        me.areaEmail.set(JSON.parse(localStorage.getItem('officeInfo')).email);
				    }
			    );
		    }else{
		    	justep.Util.hint('请选择小区', {type:'danger'});
		    }
		    
		    $('#'+this.getIDByXID("select1")).hide();
		    $('#'+this.getIDByXID("areaName")).show();
		    this.comp("changeOffice").set({label:'修改'});
		    this.isOfficeChange = false;
		    
		}

	};
	
	Model.prototype.modelLoad = function(event){
	    this.comp("output7").set({value:this.getParentModel().getCompanyName()});
	    this.comp("output6").set({value:this.getParentModel().getCompanyAddress()});
	    this.comp("output2").set({value:this.getParentModel().getCompanyCode()});
	    
		if(this.getParentModel().getUserType() == '4'){
			$('.bisnessInfo').show();	
			var imgList = this.getParentModel().getBusinessImage();
	//		debugger;
			if(imgList){
				//imgList.shift();
				//console.log(imgList);
				this.imgSrcList = imgList.concat();
				for (var i = 0;i<imgList.length;i++){
					imgList[i] = 'http://www.xjzlhy.com:81' + imgList[i];
					this.fileList.push(imgList[i]);
					this.previewImgBySrc(imgList[i],this);
				}
			}
			
			
			
			
			
			if(this.fileList.length >0){
				$("#"+this.getIDByXID("deleteBtn")).show();
			}
			
			//显示introduce
			if(this.getParentModel().getBusnessIntroduce()){
			
//				$('#'+this.getIDByXID("introduce")).html(this.getParentModel().getBusnessIntroduce());

				this.comp("introduce").val(this.getParentModel().getBusnessIntroduce());
			
			}
			
			
			
			
			//console.log(this.fileList);
				
		}else{
			$('.bisnessInfo').hide();	
		}
	};
	
	Model.prototype.modelModelConstructDone = function(event){
	       if(localStorage.getItem('officeInfo')){
	           
	    	   this.areaName.set(JSON.parse(localStorage.getItem('officeInfo')).name);
	           this.areaAddress.set(JSON.parse(localStorage.getItem('officeInfo')).address);
	           this.areaEmail.set(JSON.parse(localStorage.getItem('officeInfo')).email);
	       }
           
	};
	
	
	
	
	
	
	 //选择要添加的图片
	Model.prototype.file2Change = function(event){
	   $(".preview img").off("click");
	   var me = this;
	   me.imgSelectIndex = me.fileList.length-1;
		this.fileList.push(event.currentTarget.files[0]);
		this.addImgList.push(event.currentTarget.files[0]);
		var src = window.URL.createObjectURL(event.currentTarget.files[0]);
//		$("#"+this.getIDByXID("imgPreview")).append("<img src='"+src+"' style='margin-right:5px;' class='img-thumbnail imgUnSelect' />");
//		$(".preview img").each(function(index){
//			$(this).on("click",function(event){
//				 me.imgSelectIndex = index;
//				 $(this).toggleClass("imgUnSelect");
//				 $(this).toggleClass("imgSelect");
//				 $(this).siblings().removeClass("imgSelect");
//				 $(this).siblings().addClass("imgUnSelect");
//				 if($(this).hasClass("imgUnSelect")){
//					 me.imgSelectIndex = -1;
//				 }
//			});
//		});
//		if(this.fileList.length == 1){
//			$("#"+this.getIDByXID("deleteBtn")).show();
//		}

        this.previewImgBySrc(src, me);
        if(this.fileList.length > 0){
			$("#"+this.getIDByXID("deleteBtn")).show();
		}
	};

   
	//删除照片按钮

	Model.prototype.deleteBtnClick = function(event){
	    
	    	if(this.imgSelectIndex == -1){
	    		justep.Util.hint("请选择要删除的图片", {type:"danger"});    	
	    	}else{
	   
	    	    if(this.imgSelectIndex < this.imgSrcList.length){
	    	    //删除原来的图片
	    	    	this.imgSrcList.splice(this.imgSelectIndex,1);
	    	    
	    	    }else{
	    	       //删除新的图片
	    	    	this.addImgList.splice(this.imgSelectIndex-this.imgSrcList.length,1);
	    	    }
	    		this.fileList.splice(this.imgSelectIndex,1);
		    	$(".preview img").eq(this.imgSelectIndex).remove();
		    	this.imgSelectIndex = this.fileList.length - 1;
		        if(this.fileList.length === 0){
		        	$("#"+this.getIDByXID("deleteBtn")).hide();
		        }
	    	}
	};
	
	//修改商家信息
	Model.prototype.changeBisnessInfo = function(event){
	    var me = this;
	    
		var introduce = this.comp("introduce").val();
		var formData  = new FormData();
		if(introduce){
		    
			formData.append('introduce',introduce);
		}
		
		formData.append('originalImg',this.imgSrcList.toString().substr(0,this.imgSrcList.toString().length).replace(',','|'));//返回原来的图片
		
		//返回新的图片
		for(var i = 0;i < this.addImgList.length;i++){
			 formData.append("image"+i,this.addImgList[i]);
		}
		
		
		formData.append('id',this.getParentModel().getUserId());
		
	
		
		$.ajax({
				  url: "http://www.xjzlhy.com:81/ex_community/a/api/community/businessPic",
				  type: "POST",
				  data: formData,
				  processData: false,  // 告诉jQuery不要去处理发送的数据
				  contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
				  success:function(result){
				    //  console.log(result);
				      $(".preview").empty();
				      justep.Util.hint('修改成功', {type:'success'});
				      var images = '';
				      if('images' in result.data){
				         images = result.data.images;
				         var imageList = images.split('|');
				         for (var i = 1;i<imageList.length;i++){
							imageList[i] = 'http://www.xjzlhy.com:81' + imageList[i];
							me.fileList.push(imageList[i]);
							me.previewImgBySrc(imageList[i],me);
						}
				      }
				      me.updateBusinessInfo(images, introduce);
					  //justep.Shell.closePage();
				  }				  
				}); 
		

	};
	
	Model.prototype.previewImgBySrc = function(src,me){
	    $(".preview img").off('click');
		$("#"+me.getIDByXID("imgPreview")).append("<img src='"+src+"' style='margin-right:5px;' class='img-thumbnail imgUnSelect' />");
		$(".preview img").each(function(index){
			$(this).on("click",function(event){
				 me.imgSelectIndex = index;
				 $(this).toggleClass("imgUnSelect");
				 $(this).toggleClass("imgSelect");
				 $(this).siblings().removeClass("imgSelect");
				 $(this).siblings().addClass("imgUnSelect");
				 if($(this).hasClass("imgUnSelect")){
					 me.imgSelectIndex = -1;
				 }
			});
		});
		
	
	};
	
	
	//更新商家信息
	Model.prototype.updateBusinessInfo = function(imgSrc,introduce){
		var userInfo = JSON.parse(localStorage.getItem('userInfo'));
		if(imgSrc){
			userInfo.userBusiness.images = imgSrc;
		}
		userInfo.userBusiness.introduce = introduce;
		
		localStorage.setItem('userInfo', JSON.stringify(userInfo));
		//location.reload(true);
		
	};
	
	return Model;
});